<template>
  <div class="page-sign-up">
    <div class="columns">
      <div class="column is-4 is-offset-4">
        <h1 class="title">Sign up</h1>

        <form @submit.prevent="submitForm">
          <div class="field">
            <label>Username</label>
            <div class="control">
              <input class="input" type="text" v-model="username">
            </div>
          </div>

          <div class="field">
            <label>Password</label>
            <div class="control">
              <input class="input" type="password" v-model="password">
            </div>
          </div>

          <div class="field">
            <label>Repeat password</label>
            <div class="control">
              <input class="input" type="password" v-model="password2">
            </div>
          </div>

          <div class="notification is-danger" v-if="errors.length">
            <p v-for="error in errors" v-bind:key="error">{{error}}</p>
          </div>

          <div class="field">
            <div class="control">
              <button class="button is-dark">SignUp</button>
            </div>
          </div>

          <hr>

          Or<router-link to="/login"> click here </router-link>to Login!
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {toast} from "bulma-toast";

export default {
  name: "SignUp",
  data(){
    return {
      username:'',
      password:'',
      password2:'',
      errors:[]
    }
  },
  mounted() {
    //网页修改标题
    document.title = 'SignUp | JACKETS-SHOP'
  },
  methods:{
    submitForm(){
      this.errors = []

      if (this.username === ''){
        this.errors.push('The username is missing')
        return;
      }

      if (this.password === ''){
        this.errors.push('The password is missing')
        return;
      }

      if (this.password2 !== this.password){
        this.errors.push("The passwords don't match")
        return;
      }

      if (!this.errors.length){
        const formDate={
          username:this.username,
          password:this.password
        }

        axios
        .post(`/api/v1/users/`,formDate)
        .then(response =>{
          toast({
            message:'Account created, please login!',
            type:'is-success',
            dismissible:true,
            pauseOnHover:true,
            duration:2000,
            position:'bottom-center',
          })

          this.$router.push('/login')
        })

        .catch(error =>{
          if (error.response){
            for(const property in error.response.data ){
              this.errors.push(`${property}: ${error.response.data[property]}`)
            }
            console.log(JSON.stringify(error.response.data))
          }else if (error.message){
            this.errors.push('Something went wrong. Please try again')

            console.log(JSON.stringify(error))
          }
        })
      }
    }
  }
}
</script>

<style scoped>

</style>